package com.loong.android.sqlite;

import android.text.TextUtils;

import com.loong.android.sqlite.data.EntityVal;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Xili on 2020/3/22.
 */

public class CommonEntity {

    public static final String ID_KEY = "db_id";
    public static final String ID_COLUMN_KEY = "db_id";
    private final List<EntityVal> valList = new ArrayList<>();

    public void addValIfNotExist(String key, Object val) {
        for (EntityVal entityVal : valList) {
            if (entityVal == null || TextUtils.isEmpty(entityVal.getName())) continue;
            if (!entityVal.getName().equals(key)) continue;
            entityVal.setVal(val);
            return;
        }
        valList.add(new EntityVal(key, val));
    }

    public void addVal(String key, String val) {
        addValIfNotExist(key, val);
    }
    public void addVal(String key, Short val) {
        addValIfNotExist(key, val);
    }
    public void addVal(String key, Integer val) {
        addValIfNotExist(key, val);
    }
    public void addVal(String key, Long val) {
        addValIfNotExist(key, val);
    }
    public void addVal(String key, Float val) {
        addValIfNotExist(key, val);
    }
    public void addVal(String key, Double val) {
        addValIfNotExist(key, val);
    }
    public void addVal(String key, Boolean val) {
        addValIfNotExist(key, val);
    }

    public Object getVal(String key) {
        for (EntityVal entityVal : valList) {
            if (entityVal == null || TextUtils.isEmpty(entityVal.getName())) continue;
            if (!entityVal.getName().equals(key)) continue;
            return entityVal.getVal();
        }
        return null;
    }

    public Object getVal(int index) {
        if (index < 1 || index > valList.size()) return null;
        int i = 0;
        for (EntityVal entityVal : valList) {
            if (entityVal == null || TextUtils.isEmpty(entityVal.getName())) continue;
            i++;
            if (i < index) continue;
            return entityVal.getVal();
        }
        return null;
    }

    public void setVal(int index, Object val) {
        if (index < 1 || index > valList.size()) return;
        int i = 0;
        for (EntityVal entityVal : valList) {
            if (entityVal == null || TextUtils.isEmpty(entityVal.getName())) continue;
            i++;
            if (i < index) continue;
            entityVal.setVal(val);
            break;
        }
    }

    public List<EntityVal> getValList() {
        return this.valList;
    }

    public Long getId() {
        Object id = getVal(ID_KEY);
        if (!(id instanceof Long)) return 0L;
        return (Long) id;
    }

    public void setId(Long id) {
        addVal(ID_KEY, id);
    }

}
